package com.wsm.system.controller;

import com.wsm.common.annotation.OperateLog;
import com.wsm.common.controller.BaseController;
import com.wsm.common.domain.FileDO;
import com.wsm.common.domain.Tree;
import com.wsm.common.service.FileService;
import com.wsm.common.service.RedisService;
import com.wsm.common.utils.*;
import com.wsm.system.domain.MenuDO;
import com.wsm.system.domain.UserDO;
import com.wsm.system.mapper.UserDao;
import com.wsm.system.service.MenuService;
import com.wsm.system.service.SessionService;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.wsm.common.enums.Constant.LIMIT_LOG;

@Api(tags = "登录")
@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    UserDao userDao;
    @Autowired
    SessionService sessionService;
    @Autowired
    RedisService redisService;

    @GetMapping({"/", ""})
    String welcome() {
        return "redirect:/blog";
    }

    @OperateLog("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model) {
        UserDO user = getUser();
        List<Tree<MenuDO>> menus = menuService.listMenuTree(user.getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", user.getName());
        FileDO fileDO = fileService.get(user.getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg");
        }
        model.addAttribute("username", user.getUsername());
        return "index_v1";
    }

    @RequestMapping("/login")
    String login(HttpServletRequest request, HttpServletResponse response, Model model) {
        String cookieValue = CookieUtils.getCookieValue(request, "userId", true);
        if (cookieValue == null || "".equals(cookieValue)) {
            return "login";
        }
        UserDO userDO = userDao.get(Long.valueOf(cookieValue));
        if (userDO == null) {
            return "login";
        } else {
            String password = userDO.getPassword();
            String username = userDO.getUsername();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                return "login";
            }
            return "redirect:/index";
        }
    }

    @RequestMapping({"/forceLogin", "/forceLoginOut"})
    String forceLogin() {
        return "login";
    }

    @OperateLog("登录")
    @PostMapping("/login")
    @ResponseBody
    Result ajaxLogin(String username, String password, String verify, HttpServletRequest request, HttpServletResponse response) {
        try {
            //从session中获取随机数
            String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return Result.denyMsg("请输入验证码");
            }
            if (random.equals(verify)) {
            } else {
                return Result.denyMsg("请输入正确的验证码");
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return Result.denyMsg("验证码校验失败");
        }
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //设置cookie
            CookieUtils.setCookie(request, response, "userId", ShiroUtils.getUserId().toString());
        } catch (UnknownAccountException e) {
            return Result.denyMsg("账号不存在");
        } catch (ExcessiveAttemptsException e) {
            return Result.denyMsg("连续输入错误次数过多，请" + redisService.getExpire(LIMIT_LOG + username) + "秒后再试");
        } catch (LockedAccountException e) {
            return Result.denyMsg("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return Result.denyMsg("账号或密码不正确");
        }
        return Result.success();
    }

    /**
     * 退出
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logouts")
    String logout(HttpServletRequest request,HttpServletResponse response) {
        CookieUtils.deleteCookie(request, response, "userId");
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }
    }
}
